package xjtu.sad.zbsj.user.register;


import xjtu.sad.zbsj.common.CommonService;
import xjtu.sad.zbsj.common.MailTool;
import xjtu.sad.zbsj.common.Result;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;

@RestController
@RequestMapping("/user/register")
public class RegisterAPI {
    @Resource
    private RegisterService registerService;

    @Resource
    private CommonService commonService;

    private static String codeId = "";
    private static String emailAddress = "";

    @RequestMapping("")
    public Result addUser(@RequestBody RegisterDto dto){
        boolean ok = registerService.checkCount2(dto.getU_eml())&registerService.checkCount(dto.getU_name());
        if(ok){
            registerService.addUser(dto);
            System.out.println(dto.getU_id());
            return Result.success(dto.getU_id());
        }
        else{
            return Result.fail(Result.ERR_CODE_UNREGISTER,"fail");
        }
    }

    @RequestMapping("/nick")
    public Result examineName(@RequestBody RegisterDto dto){
        boolean ok= registerService.checkCount(dto.getU_name());
        if(ok){
            return Result.success("true");
        }
        else{
            return Result.fail(Result.ERR_CODE_BUSINESS,"false");
        }

    }

    //获取验证码
    @RequestMapping("/getCode")
    @ResponseBody
    public Result getCode(String email , HttpServletRequest request){
        //随机生成一个验证码
        System.out.println("进来了");
        Integer code=new Random().nextInt(999999);
        //request.getSession().setAttribute("code",code.toString());
        //request.getSession().setAttribute("email",email);
        codeId = code.toString();
        emailAddress = email;
        System.out.println(email);
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        MailTool.send(email,code);
                    }
                }
        ).start();
        return Result.success("success");
    }

    @RequestMapping("/emailRegister")
    public Result emailLogin(String email , String code, HttpServletRequest request){
        //String emailAddress = (String) request.getSession().getAttribute("email");
        //String codeId = (String) request.getSession().getAttribute("code");
        System.out.println("+++++++++++"+ email);
        System.out.println("+++++++++++"+codeId);
        if (email.equals(emailAddress) && code.equals(codeId)){
            System.out.println("邮箱密码匹配成功");
            return Result.success("success");
        }else {
            codeId = "";
            return Result.fail(Result.ERR_CODE_BUSINESS, "验证码错误！");
        }
    }
}



